package com.yuexunit.mobilenurse.module.PatientDetail.ui;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.imscs.barcodemanager.BarcodeManager;
import com.imscs.barcodemanager.Constants;
import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.base.AppContext;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.DocAdvice.ui.Act_DocAdvice;
import com.yuexunit.mobilenurse.module.HealthArticles.ui.Act_Article;
import com.yuexunit.mobilenurse.module.HospitalInfo.Act_HospitalInfo;
import com.yuexunit.mobilenurse.module.PatientDetail.bean.PatientPanicBean;
import com.yuexunit.mobilenurse.module.PatientDetail.bean.Patient_Patinfo;
import com.yuexunit.mobilenurse.module.PatientDetail.model.impl.PatientDetailModel;
import com.yuexunit.mobilenurse.module.PatientDetail.presenter.IPatientDetailPresenter;
import com.yuexunit.mobilenurse.module.PatientDetail.presenter.impl.PatientDetailPresenter;
import com.yuexunit.mobilenurse.module.PatientDetail.ui.view.IPatientDetailView;
import com.yuexunit.mobilenurse.module.Satisfaction.ui.Act_Satisfaction;
import com.yuexunit.mobilenurse.module.SignInput.bean.Sign_Single;
import com.yuexunit.mobilenurse.module.SignInput.ui.Act_Signs_Input;
import com.yuexunit.mobilenurse.module.SkinTest.ui.Act_SkinTestDetail;
import com.yuexunit.mobilenurse.module.Transportation.ui.Act_Transportation;
import com.yuexunit.mobilenurse.module.TxtNode.ui.Act_TxtWirte;
import com.yuexunit.mobilenurse.widget.Dialog_BloodPass;
import com.yuexunit.mobilenurse.widget.Dialog_BloodRepeat;
import com.yuexunit.mobilenurse.widget.Dialog_BloodUnpass;
import com.yuexunit.mobilenurse.widget.Dialog_Fail;
import com.yuexunit.mobilenurse.widget.FixedSwipeListView;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/8/18.
 */
public class Act_PatientDetail_M80 extends KJActivity implements IPatientDetailView ,BarcodeManager.OnEngineStatus {
    //病人基本信息组件
    @Bind(R.id.patient_pic)
    public ImageView patient_pic;
    @Bind(R.id.patient_name)
    public TextView patient_name;
    @Bind(R.id.patient_grade)
    public TextView patient_grade;
    @Bind(R.id.patient_age)
    public TextView patient_age;
    @Bind(R.id.patient_sex)
    public TextView patient_sex;
    @Bind(R.id.patient_doc)
    public TextView patient_doc;
    @Bind(R.id.patient_bed)
    public TextView patient_bed;
    @Bind(R.id.patient_date)
    public TextView patient_date;
    @Bind(R.id.patient_hospital)
    public TextView patient_hospital;
    @Bind(R.id.patient_lesion)
    public TextView patient_lesion;
    @Bind(R.id.patient_diagnose)
    public TextView patient_diagnose;
    @Bind(R.id.patient_paniclist)
    FixedSwipeListView patientPaniclist;
    //当前病人住院号
    private String Visitno;
    //日期显示格式
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private IPatientDetailPresenter presenter;
    private LoadingDialog dialog;

    //扫描号码
    String code;

    //采血成功计时
    Handler handler_blood;
    Timer time;
    TimerTask timetask;
    int countTime = 3;

    private BaseAdapter adapter;
    private ArrayList<PatientPanicBean> patientPanicBeans = new ArrayList<PatientPanicBean>();

    //扫描
    private DoDecodeThread mDoDecodeThread;
    private BarcodeManager mBarcodeManager = null;
    private final int SCANKEY_LEFT = 301;
    private final int SCANKEY_RIGHT = 300;
    private final int SCANKEY_CENTER = 302;
    private final int SCANTIMEOUT = 3000;
    private Handler mDoDecodeHandler;
    private boolean mbKeyDown = true;
    class DoDecodeThread extends Thread {
        public void run() {
            Looper.prepare();
            mDoDecodeHandler = new Handler();
            Looper.loop();
        }
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.act_patientdetail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        dialog = new LoadingDialog(aty);
        presenter = new PatientDetailPresenter(new PatientDetailModel(), this);
        Visitno = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
    }

    @Override
    public void initWidget() {
        super.initWidget();
        mDoDecodeThread = new DoDecodeThread();
        mDoDecodeThread.start();
        presenter.showPatientDetail(Visitno);
    }

    @OnClick({R.id.find_plugin_1, R.id.find_plugin_2, R.id.find_plugin_3, R.id.find_plugin_4, R.id.find_plugin_5, R.id.find_plugin_6, R.id.find_plugin_7, R.id.find_plugin_8, R.id.find_plugin_9,R.id.titlebar_img_back})
    public void PatientFunction(View view) {
        switch (view.getId()) {
            case R.id.find_plugin_1:  //医嘱
                Bundle bundle = new Bundle();
                bundle.putString("source", AppConfig.CLICK);
                showActivity(aty, Act_DocAdvice.class, bundle);
                break;
            case R.id.find_plugin_2: //体征
                showActivity(aty, Act_Signs_Input.class);
                break;
            case R.id.find_plugin_3: //皮试
                showActivity(aty, Act_SkinTestDetail.class);
                break;
            case R.id.find_plugin_4: //护理计费
                ViewInject.toast("正在研发");
                break;
            case R.id.find_plugin_5://住院档案
                showActivity(aty, Act_HospitalInfo.class);
                break;
            case R.id.find_plugin_6://满意度调查
                showActivity(aty, Act_Satisfaction.class);
                break;
            case R.id.find_plugin_7://护理笔记
                showActivity(aty, Act_TxtWirte.class);
                break;
            case R.id.find_plugin_8://健康宣教
                showActivity(aty, Act_Article.class);
                break;
            case R.id.find_plugin_9://手术转运
                showActivity(aty, Act_Transportation.class);
                break;
            case R.id.titlebar_img_back:
                finish();
                break;
        }
    }

    @Override
    public void showPatientDetail(Patient_Patinfo currentPatient) {
        //判断当前向服务器发送的病人住院号请求与服务器发回来的病人是否一致
        if (Visitno != null) {
            if (!Visitno.equals(currentPatient.getVisit_no())) {
                ViewInject.toast("服务器返回数据错误");
                return;
            }
        }

        //其中保存当前病人的床号到当前病人信息中
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE, currentPatient.getBedcode());
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME, currentPatient.getName());
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_PRE, currentPatient.getPrepay() + "");
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_TOTAL, currentPatient.getTotalfee() + "");
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_DATE, currentPatient.getAdmissiondate() + "");
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_AGE, currentPatient.getAge()+ "");

        if ("1".equals(currentPatient.getSex()) && currentPatient.getAge() > AppConfig.AGE_LIMIT) {
            patient_pic.setImageResource(R.drawable.pic_male_circle);
            PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_SEX, "男");
        } else if ("1".equals(currentPatient.getSex()) && currentPatient.getAge() < AppConfig.AGE_LIMIT) {
            patient_pic.setImageResource(R.drawable.pic_boy_circle);
            PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_SEX, "男");
        } else if ("2".equals(currentPatient.getSex()) && currentPatient.getAge() > AppConfig.AGE_LIMIT) {
            patient_pic.setImageResource(R.drawable.pic_female_circle);
            PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_SEX, "女");
        } else {
            patient_pic.setImageResource(R.drawable.pic_girl_circle);
            PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_SEX, "女");
        }

        patient_name.setText(currentPatient.getName());
        patient_grade.setText(currentPatient.getGradename() + "级");
        patient_age.setText(currentPatient.getAge() + "");
        if ("1".equals(currentPatient.getSex())) {
            patient_sex.setText("男");
        } else if ("2".equals(currentPatient.getSex())) {
            patient_sex.setText("女");
        } else {
            patient_sex.setText("不详");
        }
        patient_doc.setText(currentPatient.getMdoctorname());
        patient_bed.setText(currentPatient.getBedcode());
        patient_hospital.setText(currentPatient.getVisit_no());
        patient_lesion.setText(currentPatient.getWardname());
        patient_diagnose.setText(currentPatient.getDiagnosis());
        patient_date.setText(currentPatient.getAdmissiondate());
    }


    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                dialog.dismiss();
                break;

        }
    }

    @Override
    public void NoPatientDialog() {
        Dialog_Fail.Builder builder_fail = new Dialog_Fail.Builder(aty);
        builder_fail.setMessage("未查到该病人信息");
        builder_fail.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });

        builder_fail.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
        builder_fail.create().show();
    }

    @Override
    public void bloodDialog(int status) {
        switch (status) {
            case AppConfig.BLOOD_DIALOG_REPEAT:
                display_bloodrepeat();
                break;
            case AppConfig.BLOOD_DIALOG_UNPASS:
                display_bloodunpass();
                break;
            case AppConfig.BLOOD_DIALOG_PASS:
                display_bloodpass();
                break;
        }
    }

    @Override
    public void saveSingleTypes(ArrayList<Sign_Single> sign_singles) {
        ((AppContext) this.getApplication()).setSingleTypes(sign_singles);
    }

    private void display_bloodrepeat() {
        final Dialog_BloodRepeat.Builder dialog_repeat = new Dialog_BloodRepeat.Builder(aty);
        dialog_repeat.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
        dialog_repeat.create().show();
    }

    private void display_bloodunpass() {
        final Dialog_BloodUnpass.Builder dialog_unpass = new Dialog_BloodUnpass.Builder(aty);
        dialog_unpass.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
        dialog_unpass.create().show();
    }

    private void display_bloodpass() {
        final Dialog_BloodPass.Builder dialog_pass = new Dialog_BloodPass.Builder(aty);
        dialog_pass.create().show();
        handler_blood = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what > 0) {
                    Log.v("time", msg.what + "");
                } else {
                    countTime = 3;
                    if (time != null) {
                        time.cancel();
                        time = null;
                    }

                    if (timetask != null) {
                        timetask.cancel();
                        timetask = null;
                    }
                    dialog_pass.dismiss();
                }
                super.handleMessage(msg);
            }

        };

        time = new Timer(true);
        timetask = new TimerTask() {
            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = countTime;
                handler_blood.sendMessage(msg);

            }

        };
        time.schedule(timetask, 0, 1000);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mBarcodeManager == null) {
            // initialize decodemanager
            mBarcodeManager = new BarcodeManager(this, this);
        }
        presenter.getSingleTypes(Visitno);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mBarcodeManager != null) {
            try {
                mBarcodeManager.release();
                mBarcodeManager = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBarcodeManager != null) {
            try {

                mBarcodeManager.release();
                mBarcodeManager = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private void doScanInBackground() {
        mDoDecodeHandler.post(new Runnable() {

            @Override
            public void run() {
                if (mBarcodeManager != null) {
                    // TODO Auto-generated method stub
                    try {
                        synchronized (mBarcodeManager) {
                            mBarcodeManager.executeScan(SCANTIMEOUT);
                        }

                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
            case SCANKEY_LEFT:
            case SCANKEY_CENTER:
            case SCANKEY_RIGHT:
            case KeyEvent.KEYCODE_SLASH: // hal key
                try {
                    if (mbKeyDown) {
                        DoScan();
                        mbKeyDown = false;
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return true;
            case KeyEvent.KEYCODE_BACK:
                this.finish();
                return true;
            default:
                return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
            case SCANKEY_LEFT:
            case SCANKEY_CENTER:
            case SCANKEY_RIGHT:
            case KeyEvent.KEYCODE_SLASH: // hal key
                try {
                    mbKeyDown = true;
                    cancleScan();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return true;
            case KeyEvent.KEYCODE_BACK:
                this.finish();
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }

    private void DoScan() throws Exception {
        doScanInBackground();
    }

    private void cancleScan() throws Exception {
        if (mBarcodeManager != null) {
            mBarcodeManager.exitScan();
        }
    }

    @Override
    public void onEngineReady() {
        // TODO Auto-generated method stub
        ScanResultHandler.sendEmptyMessage(Constants.DecoderReturnCode.RESULT_DECODER_READY);
    }

    @Override
    public int scanResult(boolean suc,BarcodeManager.ScanResult result) {
        // TODO Auto-generated method stub
        Message m = new Message();
        m.obj = result;
        if (suc){
            // docode successfully
            m.what = Constants.DecoderReturnCode.RESULT_SCAN_SUCCESS;
        }else{
            m.what = Constants.DecoderReturnCode.RESULT_SCAN_FAIL;

        }
        ScanResultHandler.sendMessage(m);
        return 0;
    }

    private Handler ScanResultHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.DecoderReturnCode.RESULT_SCAN_SUCCESS:
                    String strDecodeResult = "";
                    BarcodeManager.ScanResult decodeResult = (BarcodeManager.ScanResult) msg.obj;

                    String result = decodeResult.result;
                    if (mBarcodeManager != null) {
                        mBarcodeManager.beepScanSuccess();
                    }
                    if (!result.equals("")) {
                        if (result.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_PTSM_RULE))) {
                            String type_tag = result.substring(8, 9);
                            if (type_tag.equals(AppConfig.TAG_INJECTION)) {
                                Bundle bundle = new Bundle();
                                bundle.putString("source", AppConfig.SEARCH);
                                bundle.putString("id", result);
                                bundle.putString("type", AppConfig.INJECTION);
                                showActivity(aty, Act_DocAdvice.class, bundle);
                            } else if (type_tag.equals(AppConfig.TAG_DISPENSING)) {
                                Bundle bundle = new Bundle();
                                bundle.putString("source", AppConfig.SEARCH);
                                bundle.putString("id", result);
                                bundle.putString("type", AppConfig.DISPENSING);
                                showActivity(aty, Act_DocAdvice.class, bundle);
                            }
                        } else if (result.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_CX_RULE))) {
                            code = result;
                            presenter.collect(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO), code,
                                    PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID));
                        } else {
                            Toast.makeText(aty, "条码无效!", Toast.LENGTH_LONG).show();
                        }
                    }
                    break;

                case Constants.DecoderReturnCode.RESULT_SCAN_FAIL: {
                    if (mBarcodeManager != null) {
                        mBarcodeManager.beepScanFail();
                    }
                }
                break;
                case Constants.DecoderReturnCode.RESULT_DECODER_READY: {
                }
                break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };

}
